var express = require('express');
var router = express.Router();
const { cateModel, flowerModel, cartModel, userModel, addressListModel,orderModel } = require('../model/model')

router.get('/cate', async (req, res) => {
    let cate = await cateModel.find()
    res.send({
        code: 200, cate
    })
})

router.get('/list', async (req, res) => {
    let { cate } = req.query
    let arr = []
    if (cate) arr.push({
        cate
    })
    let list = await flowerModel.find({ $and: arr })
    res.send({
        code: 200, list
    })
})

router.post('/addCart', async (req, res) => {
    await cartModel.create(req.body)
    res.send({
        code: 200,
    })
})

router.get('/cart', async (req, res) => {
    let cart = await cartModel.find()
    res.send({
        code: 200, cart
    })
})

router.post('/update', async (req, res) => {
    let body = req.body
    let _id = body._id
    await cartModel.updateOne({ _id }, body)
    res.send({
        code: 200,
    })
})


router.get('/login', async (req, res) => {
    let user = await userModel.find()
    let id = user[0]._id
    let address = user[0].address
    if (address == []) {    
        res.send({
            code: 400,
            msg: "新用户地址为空"
        })
    } else {
        address.forEach(async (item, index) => {
            let adress = await addressListModel.find({ _id: item })
            console.log(adress);
            if (adress[0].isdefault == true) {
                console.log(adress);
                res.send({
                    code: "200",
                    id,
                    adress
                })
            }
        })
    }
})

router.get('/find',async(req,res)=>{
    let {id} = req.query
    // console.log(_id);
    
    let flo = await flowerModel.find({_id:id})
    console.log(flo);
    res.send({
        code:200,flo
    })
})

router.post('/addOrder',async(req,res)=>{
    await orderModel.create(req.body)
    res.send({
        code:200,
    })
    
})




module.exports = router